<template>
  <div class="userinfo_pages">
    <cp-nav-bar title="群聊信息" left-arrow></cp-nav-bar>
    <van-cell-group>
      <van-cell>
        <template #title
          ><div>
            <template v-for="item in userInfo?.members" :key="item.user_id">
              <van-image
                :src="item.user_avatar"
                width="45px"
                height="45px"
                radius="4px"
                style="margin-right: 3px"
              ></van-image>
            </template></div
        ></template>
      </van-cell>
      <van-cell title="群名称" :value="userInfo?.groupInfo?.group_name"></van-cell>
      <van-cell title="注册时间" :value="formatTime(userInfo?.groupInfo?.created_at)"></van-cell>
    </van-cell-group>

    <button
      class="delete-friend-btn"
      @click="deleteFriend"
      v-if="store.user?.user_id === createAuth?.user_id"
    >
      删除群聊
    </button>
  </div>
</template>
<script setup lang="ts">
import { getGroupInfo, deleteGroup } from '@/services/friend'
import { formatTime } from '@/utils/format'
import { showConfirmDialog, showToast } from 'vant'
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores'

const store = useUserStore()

const userInfo = ref()
const route = useRoute()
const router = useRouter()
const getInfo = async () => {
  const groupId = route.params.id as string
  const res = await getGroupInfo(groupId)
  userInfo.value = res.data
}
getInfo()
const deleteFriend = () => {
  showConfirmDialog({
    title: '是否删除群聊'
  })
    .then(async () => {
      // on confirm
      await deleteGroup(route.params.id as string)
      showToast('删除成功')
      router.push('/home')
    })
    .catch(() => {
      // on cancel
    })
}
const createAuth = computed(() => {
  return userInfo.value?.members.find((item: { role: string }) => item.role === 'admin')
})
</script>
<style lang="scss" scoped>
.userinfo_pages {
  padding-top: 40px;
  height: 100vh;
  box-sizing: border-box;
  background-color: var(--bg-primary);
}
.delete-friend-btn {
  color: red;
  width: 100%;
  border: none;
  text-align: center;
  background-color: var(--bg-tertiary);
  margin-top: 30px;
}
</style>
